package com.prs.crm.service.stock.impl;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.dao.stock.ProductClassDao;
import com.prs.crm.domain.stock.ClassAttribute;
import com.prs.crm.domain.stock.ProductClass;
import com.prs.crm.domain.sys.ChooseItem;
import com.prs.crm.domain.sys.FieldUI;
import com.prs.crm.service.impl.BaseServiceImpl;
import com.prs.crm.service.stock.ProductClassService;
import com.prs.crm.service.sys.FieldUIService;

public class ProductClassServiceImpl extends
		BaseServiceImpl<ProductClass, ProductClassDao> implements
		ProductClassService {

	@Autowired
	private FieldUIService fieldUIService;

	public void setFieldUIService(FieldUIService fieldUIService) {
		this.fieldUIService = fieldUIService;
	}

	public FieldUIService getFieldUIService() {
		return fieldUIService;
	}

	public Collection<ProductClass> getProductClasses() {
		return this.getDao().getProductClasses();
	}

	public Collection<ProductClass> findRootClasses() {
		return this.getDao().findRootClasses();
	}

	@SuppressWarnings("null")
	public void saveAttribute(ProductClass pls, ClassAttribute attr) {

		if (pls == null) {
			// pls.addAttribute(attr);
		} else {

			if (pls.getAttributes() == null) {
				pls.addAttribute(attr);
			} else {
				if (!pls.getAttributes().contains(attr)) {
					pls.addAttribute(attr);
				}
			}
		}
		if (attr.getUi() == null)
			attr.setUi(new FieldUI());
		attr.setProductClass(pls);
		super.save(pls);
	}

	public void removeAttribute(ProductClass pls, ClassAttribute attr) {
		if (pls.getAttributes() != null) {
			pls.getAttributes().remove(attr);
			super.save(pls);
		}
	}

	public void removeAttributes(Integer[] attrIds) {
		this.getDao().removeAttributes(attrIds);
	}

	public void saveAttrChooseItem(ClassAttribute attr, String value) {
		this.getFieldUIService().addChooseItem(attr.getUi(), value, value);
	}

	public void removeAttrItem(ClassAttribute attr, ChooseItem item) {
		this.getFieldUIService().removeChooseItem(attr.getUi(), item);
	}

	public ClassAttribute getAttribute(Integer attrId) {
		return this.getDao().getAttribute(attrId);
	}

}
